'use strict';
let mongoose = require('mongoose');

let schema = new mongoose.Schema({
    weChatUserId:{
        type: String,
        index: {
            unique: false
        }
    },
    id: {
        type: Number,
        required: true,
        index: {
            unique: true
        }
    },
    name: {
        type: String,
        required: true,
        index: {
            unique: false
        }
    },
    idCard: { //身份证号码
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    sex: {
        type: String,
        "default": '男'
    },
    province: String, //省
    city: String, //市
    area:String, //区
    workType: { //工种数组
        type: Array,
        required: false,
        index: {
            unique: false
        }
    },
    expectCities:{
        type: Array,
        required: false,
        index: {
            unique: false
        }
    },
    phone: { //手机号码
        type: String,
        required: false,
        index: {
            unique: false
        }
    },
    status: {
        type: Number,
        "default": 0
    }
});
schema.index({name: 1});
schema.index({workType: 1});

schema.statics = {
    //小程序用户的注册流程
    getRandomId: async function () {
        let id = Math.floor(Math.random() * 900000) + 100000;
        let user = await this.findOne({id: id});
        if (!!user) {
            return await this.getRandomId();
        } else {
            return id;
        }
    },

    /**
     * 新增工人
     * @param workerData -- 工人对象信息
     * @returns {Promise<void>}
     */
    addWorker: async function (workerData) {
        let autoNumber = mongoose.models['AutoNumber'];
        let worker = await this.findOne({idCard: workerData.idCard});
        if (!worker) {
            let n = await autoNumber.getNewNumber('Worker');
            return await this.create(Object.assign(workerData, {id: n}));
        }
        return false;
    },
    /**
     * 修改工人 -- 工人对象信息
     * @param workerData
     * @returns {Promise<void>}
     */
    modifyWorker: async function (workerData) {
        let worker = await this.findOne({idCard: workerData.idCard});
        if (!!worker) {
            return await this.updateOne({_id: worker._id}, {$set: workerData}).exec();
        }
        return false;
    },
    /**
     * 删除工人 -- 工人对象信息
     * @param workerData
     * @returns {Promise<void>}
     */
    deleteWorker: async function (workerData) {
        let worker = await this.findOne({idCard: workerData.idCard});
        if (!!worker) {
            await this.remove({idCard: workerData.idCard});
        } else {
            return false;
        }
        return true;
    },
    /**
     * 查找工人 -- 工人对象信息
     * @param workerData
     * @returns {Promise<void>}
     */
    findWorkers: async function (workerData) {
        let workers = [];
        let queryData = {};
        let workersCount = 0;
        // 身份证和联系电话都是唯一的
        if (workerData.idCard && workerData.idCard !== '') {
            queryData.idCard = eval('/' + workerData.idCard + '/i');
        }
        if (workerData.telPhone && workerData.telPhone !== '') {
            queryData.telPhone = eval('/' + workerData.telPhone + '/i');
        }
        // 姓名、籍贯、工种 需要模糊查询
        if (workerData.name && workerData.name !== '') {
            queryData.name = eval('/' + workerData.name + '/i');
        }
        if (workerData.jgProvince && workerData.jgProvince !== '') {
            queryData.jgProvince = eval('/' + workerData.jgProvince + '/i');
        }
        if (workerData.workType && workerData.workType.length !== 0) {
            queryData.workType = {$all: workerData.workType};
        }
        if (queryData.name === '' && queryData.jgProvince === '' && queryData.workType === '') {
            workersCount = await this.find({}).countDocuments();
            workers = await this.find({}).sort({'_id': -1}).limit(parseInt(workerData.limit)).skip(parseInt(workerData.skip));
        } else {
            workersCount = await this.find(queryData).countDocuments();
            workers = await this.find(queryData).sort({'_id': -1}).limit(parseInt(workerData.limit)).skip(parseInt(workerData.skip));
        }
        if (!!workers) {
            return {workers: workers, total: workersCount};
        }
        return false;
    },
    /**
     * 全部工人信息 -- 工人对象信息
     * @returns {Promise<void>}
     */
    showWorkers: async function (params) {
        let workersCount = await this.find({}).countDocuments();
        let workers = await this.find({}).sort({'_id': -1}).limit(parseInt(params.limit)).skip(parseInt(params.skip));
        if (!!workers) {
            return {workers: workers, total: workersCount};
        } else {
            return false;
        }

    },

    list:async function(page,pageCount,queryObj={},sortObj={_id:-1}){
        let total = await this.find(queryObj).countDocuments();
        let rows=await this.find(queryObj).sort(sortObj).skip((page-1)*pageCount).limit(pageCount);
        return {total:total,rows:rows};
    },
    add:async function(obj){
        let worker = await this.findOne({idCard: obj.idCard});
        if (!worker) {
            let n = await autoNumber.getNewNumber(modelName);
            await this.create(Object.assign(obj, {id: n}));
        }else{
            throw new Error('身份证号码已经被使用！');
        }
    }
};

module.exports = schema;